package com.example.electricbicycle.controller;

import com.example.electricbicycle.po.PurchaseOrder;
import utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/InboundQueryServlet")
public class InboundQueryServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<PurchaseOrder> inboundList = new ArrayList<>();
        int page = 1;
        int pageSize = 10;
        int totalPages = 0;
        boolean searchPerformed = false;

        String vIdParam = req.getParameter("v_id");

        // 只有当提供了VID参数时才执行查询
        if (vIdParam != null && !vIdParam.trim().isEmpty()) {
            searchPerformed = true;

            try (Connection conn = DBUtils.getConnection()) {
                // 分页参数处理
                String pageParam = req.getParameter("page");
                if (pageParam != null && !pageParam.isEmpty()) {
                    page = Integer.parseInt(pageParam);
                }

                // 获取总记录数
                String countSql = "SELECT COUNT(*) AS total FROM purchase_order WHERE status = 1 AND v_id = ?";
                int totalRecords = 0;

                try (PreparedStatement countPstmt = conn.prepareStatement(countSql)) {
                    countPstmt.setInt(1, Integer.parseInt(vIdParam.trim()));

                    try (ResultSet countRs = countPstmt.executeQuery()) {
                        if (countRs.next()) {
                            totalRecords = countRs.getInt("total");
                        }
                    }
                }

                // 计算总页数
                totalPages = (int) Math.ceil((double) totalRecords / pageSize);

                // 确保当前页码在有效范围内
                if (page < 1) page = 1;
                if (page > totalPages && totalPages > 0) page = totalPages;

                // 只有当总记录数大于0时才查询数据
                if (totalRecords > 0) {
                    String dataSql = "SELECT * FROM purchase_order WHERE status = 1 AND v_id = ? " +
                            "ORDER BY create_time DESC LIMIT ? OFFSET ?";

                    try (PreparedStatement dataPstmt = conn.prepareStatement(dataSql)) {
                        dataPstmt.setInt(1, Integer.parseInt(vIdParam.trim()));
                        dataPstmt.setInt(2, pageSize);
                        dataPstmt.setInt(3, (page - 1) * pageSize);

                        try (ResultSet rs = dataPstmt.executeQuery()) {
                            while (rs.next()) {
                                inboundList.add(new PurchaseOrder(
                                        rs.getInt("id"),
                                        rs.getInt("user_id"),
                                        rs.getInt("v_id"),
                                        rs.getInt("quantity"),
                                        rs.getInt("status"),
                                        rs.getDate("create_time")
                                ));
                            }
                        }
                    }
                }
            } catch (SQLException | NumberFormatException e) {
                e.printStackTrace();
                // 处理异常情况，可以设置错误信息
                req.setAttribute("errorMessage", "查询过程中出现错误: " + e.getMessage());
            }
        }

        req.setAttribute("inboundList", inboundList);
        req.setAttribute("currentPage", page);
        req.setAttribute("totalPages", totalPages);
        req.setAttribute("searchPerformed", searchPerformed);
        req.setAttribute("v_id", vIdParam); // 回显搜索条件

        req.getRequestDispatcher("/warehouse/inboundQuery.jsp").forward(req, resp);
    }
}